package cn.stylefeng.guns.modular.demo.excel.listener.aslikang;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.dao.entity.ImportView;
import cn.stylefeng.guns.dao.service.IImportViewService;
import cn.stylefeng.guns.modular.demo.excel.domain.RealTimeInventoryExcelVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 阿斯利康采购数据
 */
@Slf4j
public class RealTimeInventoryListener implements ReadListener<RealTimeInventoryExcelVO> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    private List<ImportView> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    private List<String> errorList;
    IImportViewService importViewService;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param importViewService
     */
    public RealTimeInventoryListener(IImportViewService importViewService, List<String> errorList) {
        this.importViewService = importViewService;
        this.errorList = errorList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(RealTimeInventoryExcelVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        ImportView importView = o2o(data);

        cachedDataList.add(importView);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private ImportView o2o(RealTimeInventoryExcelVO data) {
        Integer num = data.getNum();
        String batch = data.getBatch();
        String productCode = data.getProductCode();
        String storeCode = data.getStoreCode();
        ImportView importView = new ImportView();
        importView.setInfo(JSON.toJSONString(data));
        importView.setNum1(num);
        importView.setTemplateType("realTimeInventory");
        importView.setProCode(productCode);
        importView.setStoCode(storeCode);
        importView.setStr1(batch);
        return importView;
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        } else {
            log.info("数据错误解析错误", exception);
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        try {
            log.info("{}条数据，开始存储数据库！", cachedDataList.size());
            importViewService.saveBatch(cachedDataList);
            log.info("存储数据库成功！");
        } catch (Exception e) {
            log.info("数据错误", e);
            throw e;
        }
    }

}
